package com.sl.designmode.singleton;

import java.io.ObjectStreamException;
import java.io.Serializable;

/**
 * author： suliang
 * 2022/11/28 15:37
 * describe : 单例模式的其中实现
 */
// 饿汉式 类加载的时候就进行了初始化
/*public class Singleton implements Serializable {

    private static Singleton instance = new Singleton() ;

    private Singleton(){}

    public static Singleton getInstance(){
        return instance ;
    }
    //防止单例对象在反序列化时重新生成对象
    private Object readResolve() throws ObjectStreamException {
        return instance ;
    }
}*/
/**
 * 懒汉式 线程不安全
*/
/*public class Singleton {
    //懒汉式
    private static Singleton instance ;

    private Singleton(){}

    public static Singleton getInstance(){
        if (instance == null){
            instance = new Singleton();
        }
        return instance ;
    }
}*/
/**
 * 懒汉式 方法加锁 线程安全
*/
/*public class Singleton {
    //懒汉式
    private static Singleton instance ;

    private Singleton(){}

    public static synchronized Singleton getInstance(){
        if (instance == null){
            instance = new Singleton();
        }
        return instance ;
    }
}*/

/**
 *  懒汉式 DCL 线程安全
 */
/*public class Singleton {
    //volatile 修饰变量，防止指令重排
    private static volatile Singleton instance ;

    private Singleton(){}

    public static  Singleton getInstance(){
        if (instance == null){
            synchronized (Singleton.class){
                if (instance == null){
                    instance = new Singleton();
                }
            }
        }
        return instance ;
    }
}*/

import java.io.ObjectStreamException;

/**
 * 静态内部类
 */
/*public class Singleton {

    private Singleton(){}

    private static class SingletonHolder{
        private static final Singleton instance = new Singleton() ;
    }

    public static Singleton getInstance(){
        return SingletonHolder.instance;
    }
}*/

//import java.util.concurrent.atomic.AtomicReference;
//
///**
// *  CAS模式 : 存在忙等的问题，可能会造成 CPU 资源的浪费
// */
//public class Singleton {
//
//    private static AtomicReference<Singleton> INSTANCE = new AtomicReference<Singleton>() ;
//
//    private Singleton(){}
//
//    public static final Singleton getInstance(){
//           while (true){
//               Singleton instance = INSTANCE.get() ;
//               if (null == instance){
//                   INSTANCE.compareAndSet(null,new Singleton());
//               }
//               return INSTANCE.get() ;
//           }
//    }
//}


/**
 *  枚举实现单例
 */
public enum Singleton {
    //定义一个枚举，代表Singleton的一个实例
    INSTANCE ;

    public void doSomething(){
        System.out.println("do something");
    }
    //假设在外部调用
    void test(){
        Singleton.INSTANCE.doSomething();
    }
}
